/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
export const getStore = name => {
  if (!name) return
  return window.localStorage.getItem(name)
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return
  window.localStorage.removeItem(name)
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  res.forEach((value, index, array) => {
    if (value.children === undefined) {
      value.children = []
    }
  })
  return res
}

/**
 * 查询树形数组中某个元素的路径
 * @param data
 * @param id
 * @param indexArray
 * @returns {*}
 */
export function findIndexArray (data, id, indexArray) {
  let arr = Array.from(indexArray)
  for (let i = 0, len = data.length; i < len; i++) {
    arr.push(data[i])
    if (data[i].menuId === id) {
      return arr
    }
    let children = data[i].list
    if (children && children.length) {
      let result = findIndexArray(children, id, arr)
      if (result) return result
    }
    arr.pop()
  }
  return false
}

/**
 * 判断两个对象是否一致
 * @param {Object} o1
 * @param {Object} o2
 */
export function veq (o1, o2) {
  var props1 = Object.getOwnPropertyNames(o1)
  var props2 = Object.getOwnPropertyNames(o2)
  if (props1.length !== props2.length) {
    return false
  }
  for (var i = 0, max = props1.length; i < max; i++) {
    var propName = props1[i]
    if (o1[propName] !== o2[propName]) {
      return false
    }
  }
  return true
}

/**
 * 将base64中的数据部分转换为file
 * 例：
 * @param fileName 文件名
 * @param fileType 文件类型
 * @param dataUrl 组件获取base64原始数据；格式如上
 * @returns {*}
 */
export function dataURLtoFile (fileName, fileType, dataUrl) {
  let arr = dataUrl.split(',')
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, {
    type: fileType
  })
}

/**
 * 判断对象数组中是否存在id，对象存在id属性
 * @param array
 * @param id
 * @returns {boolean}
 */
export function isExist (array = [], id) {
  var itemCount = 0
  array.forEach(item => {
    if (item.id === id) {
      itemCount = itemCount + 1
    }
  })
  if (itemCount > 0) {
    return true
  } else {
    return false
  }
}
